<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.title"
        placeholder="名称"
        style="width: 200px"
        class="filter-item"
        maxlength="50"
        show-word-limit
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.appname"
        placeholder="AppName"
        style="width: 200px"
        class="filter-item"
        maxlength="64"
        show-word-limit
        @keyup.enter.native="handleFilter"
      />
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加执行器
      </el-button>

      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-refresh"
        @click="getList"
      >
        刷新列表
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="序号" type="index" align="center" width="50">
      </el-table-column>
      <el-table-column
        label="名称"
        min-width="10%"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="{ row }">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="AppName"
        min-width="10%"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="{ row }">
          <span>{{ row.appname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" min-width="5%" align="center">
        <template slot-scope="{ row }">
          <span>{{ typeMap[row.addressType] }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="地址"
        min-width="10%"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="{ row }">
          <span>{{ row.addressList }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最近状态更新时间" min-width="10%" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.updateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="10%"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button
            :disabled="row.type == 1"
            size="mini"
            @click="handleUpdate(row)"
          >
            编辑
          </el-button>
          <el-button
            v-if="row.status != 'deleted'"
            size="mini"
            type="danger"
            @click="handleExecutorDelete(row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="tempData"
        label-position="left"
        label-width="120px"
        style="width: 450px; margin-left: 50px"
      >
        <el-form-item prop="id" v-show="false">
          <el-input v-model="tempData.id" />
        </el-form-item>
        <el-form-item prop="title" label="名称">
          <el-input
            v-model="tempData.title"
            placeholder="执行器名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item prop="appname" label="AppName">
          <el-input
            v-model="tempData.appname"
            placeholder="AppName"
            maxlength="64"
            show-word-limit
          />
        </el-form-item>
        <el-form-item prop="addressType" label="类型">
          <el-select
            class="filter-item"
            placeholder="请选择执行器类型"
            v-model="tempData.addressType"
          >
            <el-option label="自动注册" value="0"></el-option>
            <el-option label="手动注册" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="addressList" label="地址">
          <el-input
            v-model="tempData.addressList"
            :rows="5"
            type="textarea"
            placeholder="执行器地址列表，多地址逗号分隔，格式：http://127.0.0.1:9999,http://127.0.1.1:9999"
            :disabled="tempData.addressType == 0"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close"> 取消 </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import {
  listExecutor,
  addExecutor,
  deleteExecutor,
  updateExecutor,
} from "@/api/executor";

const executorTypeOptions = [
  { key: 0, display_name: "自动注册" },
  { key: 1, display_name: "手动注册" },
];

export default {
  components: { Pagination },
  data() {
    return {
      tableKey: 0,
      //列表总数
      total: 0,
      //执行器列表加载标识位
      listLoading: true,
      //执行器列表
      list: [],
      //执行器查询参数
      listQuery: {
        page: 1,
        limit: 20,
        appname: undefined,
        title: undefined,
      },
      //执行器类型选项
      executorTypeOptions,
      tempData: {
        addressType: 1,
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "添加",
      },
      rules: {
        type: [
          { required: true, message: "请选择执行器类型", trigger: "change" },
        ],
        title: [
          { required: true, message: "请输入执行器名称", trigger: "change" },
          {
            min: 4,
            max: 50,
            message: "长度在 4 到 50 个字符",
            trigger: "blur",
          },
        ],
        appname: [
          { required: true, message: "请输入执行器AppName", trigger: "change" },
          {
            min: 4,
            max: 50,
            message: "长度在 4 到 64 个字符",
            trigger: "blur",
          },
        ],
      },
      downloadLoading: false,
      typeMap: ["自动注册", "手动注册"],
      statusMap: ["失效", "正常"],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //获取列表
    async getList() {
      this.listLoading = true;
      const data = await listExecutor(this.listQuery).then((response) => {
        return response.data;
      });
      this.list = data.list;
      this.total = data.total;
      let maxPage = Math.ceil(this.total / this.listQuery.limit);
      if (this.listQuery.page > maxPage) {
        this.listQuery.page = maxPage;
        this.getList();
      }
      setTimeout(() => {
        this.listLoading = false;
      }, 1 * 1000);
    },
    //搜索
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    //弹出添加框
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    //添加执行器
    createData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          addExecutor(this.tempData).then((response) => {
            if (response) {
              this.$notify({
                message: "添加成功",
                type: "success",
                duration: 2000,
              });
              this.close();
              this.getList();
            }
          });
        }
      });
    },
    //更新执行器
    async updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          updateExecutor(this.tempData).then((response) => {
            if (response) {
              this.$notify({
                message: "更新成功",
                type: "success",
                duration: 2000,
              });
              this.close();
              this.getList();
            }
          });
        }
      });
    },
    //关闭对话框
    close() {
      this.dialogFormVisible = false;
      this.resetTemp();
    },
    //初始化对话框
    resetTemp() {
      this.tempData = {
        uuid: undefined,
        name: undefined,
        addressType: "1",
        host: undefined,
      };
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleUpdate(row) {
      this.resetTemp();
      this.tempData = Object.assign({}, row);
      this.tempData.addressType += "";
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    //删除执行器
    async handleExecutorDelete(id) {
      const confirmRes = await this.$confirm(
        "此操作将永久删除该数据, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => console.log(err));
      if (confirmRes == "confirm") {
        this.listLoading = true;
        let response = await deleteExecutor(id);
        if (response) {
          this.$notify({
            message: "删除成功",
            type: "success",
            duration: 2000,
          });
        } else {
          this.$notify({
            message: "删除失败",
            type: "error",
            duration: 2000,
          });
        }
        this.getList();
      }
    },
    //同步执行器
    async handleSync() {},
  },
};
</script>
